package com.help10000.rms.ui.activitys.mine.user_info

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.amir.common.api.ApiContents
import com.amir.common.beans.BaseResult
import com.amir.common.beans.LogOffResult
import com.amir.common.beans.UserInfoData
import com.amir.common.utils.Constant
import com.amir.common.utils.ImageHelper
import com.amir.common.utils.SPUtils
import com.amir.common.utils.ToastUtil
import com.amir.common.weight.DuplicateClickProxy
import com.help10000.rms.R
import com.help10000.rms.common.WeChatPresenter
import com.help10000.rms.config.globalData
import com.help10000.rms.mvp.presenter.UserInfoPresenter
import com.help10000.rms.mvp.view.UserInfoView
import com.help10000.rms.ui.activitys.logins.LoginActivity
import com.help10000.rms.ui.activitys.mine.user_info.nickname.UpdateNickNameActivity
import com.help10000.rms.ui.activitys.mine.user_info.password.ChangePwdActivity
import com.help10000.rms.ui.base.BaseActivity
import com.help10000.rms.ui.utils.PageUtils
import com.lxj.xpopup.XPopup
import com.ypx.imagepicker.ImagePicker
import com.ypx.imagepicker.bean.MimeType
import kotlinx.android.synthetic.main.activity_user_info.*
import java.io.File

class UserInfoActivity : BaseActivity<UserInfoPresenter, UserInfoView>(), UserInfoView,View.OnClickListener {

    override fun getlayoutId(): Int {
        return R.layout.activity_user_info
    }

    override fun initView() {

    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    override fun initListener() {
        editNickNameTv.setOnClickListener(DuplicateClickProxy(this))
        editPwdTv.setOnClickListener(DuplicateClickProxy(this))
        editAvatarLayout.setOnClickListener(DuplicateClickProxy(this))
        logoff.setOnClickListener(DuplicateClickProxy(this))
        if (!globalData.userInfo?.UserLogo.isNullOrEmpty()) {
            ImageHelper.displayCircleImage(
                mContext,
                "${ApiContents.ImageUrl}${globalData.userInfo?.UserLogo}",
                avatarImageView
            )

        }

    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.editAvatarLayout -> {
                ImagePicker.withMulti(WeChatPresenter())//设置presenter
                    .setMaxCount(1)//设置选择数量
                    .showCamera(true)//设置显示拍照
                    .setCropRatio(1, 1)
                    .setColumnCount(4)//设置列数
                    .mimeTypes(MimeType.ofImage())//设置需要加载的文件类型
                    .filterMimeTypes(MimeType.GIF)//设置需要过滤掉的文件类型
                    .crop(mContext as Activity?) { items -> //图片剪裁回调，主线程
                        //注意：剪裁回调里的ImageItem中getCropUrl()才是剪裁过后的图片地址
                        if (items.size > 0) {
                            showLoading()
                            var url = items[0].cropUrl
                            mPresenter.upFile(File(url))
                        }
                    }
            }
            R.id.editNickNameTv -> {
                startActivity(Intent(mContext, UpdateNickNameActivity::class.java))
            }
            R.id.editPwdTv -> {
                startActivity(Intent(mContext, ChangePwdActivity::class.java))
            }
            R.id.logoff ->{
                XPopup.Builder(this)
                    .asConfirm(
                        null, "账号被注销后，将退出本系统，确认要注销吗？"
                    ) {
                        val accessToken = SPUtils.getString(Constant.AccessToken) ?: ""
                        if (accessToken.isNotEmpty()) {
                            mPresenter.logOff()
                        } else {
                            ToastUtil.show("获取令牌失败，请重新登录")
                        }
                    }.show()
            }
        }
    }


    override fun userInfoSucc(t: UserInfoData) {
        ImageHelper.displayCircleImage(
            mContext,
            "${ApiContents.ImageUrl}${t.UserInfo.UserLogo}",
            avatarImageView
        )
    }
    override fun onLogOffSuccess(result: LogOffResult) {
        SPUtils.remove(Constant.CmpyCode)
        SPUtils.remove(Constant.pwd)
        SPUtils.remove(Constant.accountName)
        SPUtils.remove(Constant.encodePassword)
        SPUtils.remove(Constant.nonceStr)
        SPUtils.remove(Constant.read_privacy)
        SPUtils.remove(Constant.AccessToken)

        globalData.userInfo = null
        globalData.token = null
        globalData.Cmpy = null

        ToastUtil.show("账号注销成功")
        val loginIntent = Intent(mContext, LoginActivity::class.java)
        // 关键 Flag：清除当前所有任务栈，并创建新任务栈
        loginIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(loginIntent)
        finish()
    }

    // 处理注销账号失败的回调
    override fun onLogOffFailure(message: String) {
        ToastUtil.show(message)
    }

    override fun loginOutSuccess(t: BaseResult) {
        SPUtils.remove(Constant.CmpyCode)
        SPUtils.remove(Constant.pwd)
        SPUtils.remove(Constant.accountName)
        SPUtils.remove(Constant.encodePassword)
        SPUtils.remove(Constant.nonceStr)
        SPUtils.remove(Constant.read_privacy)
        SPUtils.remove(Constant.AccessToken) // 最后清除 AccessToken

//        globalData.userInfo = null
//        globalData.token = null
//        globalData.Cmpy = null
        PageUtils.jumpToActivity(mContext, LoginActivity::class.java) // 跳登录页
        finish() // 关闭当前页面，避免退回
    }

    override fun createPresenter(): UserInfoPresenter {
        return UserInfoPresenter(this)
    }
    override fun onAvatarUpload(fileUrl: String) {
        mPresenter.updateAvatar(fileUrl)
    }

    override fun onAvatarUpdateSuccess() {
        ToastUtil.show("头像修改成功")
        mPresenter.initUserInfo()
    }



}